﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyWeb.Business;
using MyWeb.Data;
using MyWeb.Datamining.SearchImage;

namespace MyWeb.Admin.Usercontrols
{
    public partial class ucProductManager : UserControl
    {
        private readonly clsAlgorithm _algorithm = new clsAlgorithm();
        private readonly DistributionService _distributionService = new DistributionService();
        private readonly List<string[]> _filelist = new List<string[]>();
        private readonly GroupProductService _groupProductService = new GroupProductService();
        private readonly ProductImgService _productImgService = new ProductImgService();
        private readonly ProductService _productService = new ProductService();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadDll();
                int insert = Int32.Parse(Request.QueryString["in"]);
                if (insert == 1)
                {
                    RefreshControl();
                }
                else
                {
                    string id = Request.QueryString["id"];
                    DataTable dt = _productService.Product_GetById(id);
                    DataTable dtImgs = _productImgService.ProductImg_GetByProductId(id);
                    txtId.ReadOnly = true;
                    txtId.Text = dt.Rows[0]["id"].ToString();
                    txtName.Text = dt.Rows[0]["name"].ToString();
                    CKEditor1.Text = dt.Rows[0]["detail"].ToString();
                    txtImage.Text = dt.Rows[0]["image"].ToString();
                    txtPrice.Text = dt.Rows[0]["price"].ToString();
                    txtPriceNew.Text = dt.Rows[0]["pricenew"].ToString();
                    txtDate.Text = dt.Rows[0]["date"].ToString();
                    string image = dt.Rows[0]["image"].ToString();
                    txtOrder.Text = dt.Rows[0]["order"].ToString();
                    ddlGroupProduct.SelectedValue = dt.Rows[0]["groupproduct_id"].ToString();
                    ddlDistribution.SelectedValue = dt.Rows[0]["distribution_id"].ToString();
                    ckCongbo.Checked = Int32.Parse(dt.Rows[0]["status"].ToString()) == 0;
                    gvImage.DataSource = dtImgs;
                    gvImage.DataBind();
                    for (int i = 0; i < gvImage.Rows.Count; i++)
                    {
                        var hfImg = (HiddenField) gvImage.Rows[i].FindControl("HfImg");
                        if (hfImg.Value == image)
                        {
                            var rdoCheck = (RadioButton) gvImage.Rows[i].FindControl("rdoCheck");
                            rdoCheck.Checked = true;
                            break;
                        }
                    }
                }
            }
        }

        private void RefreshControl()
        {
            txtId.Text = string.Empty;
            txtName.Text = string.Empty;
            CKEditor1.Text = string.Empty;
            txtImage.Text = string.Empty;
            txtOrder.Text = string.Empty;
            txtPrice.Text = string.Empty;
            txtPriceNew.Text = string.Empty;
            txtDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
        }

        private void LoadDll()
        {
            ddlGroupProduct.DataSource = _groupProductService.GroupProduct_GetByAll();
            ddlGroupProduct.DataTextField = "name";
            ddlGroupProduct.DataValueField = "id";
            ddlGroupProduct.DataBind();

            ddlDistribution.DataSource = _distributionService.Distribution_GetByAll();
            ddlDistribution.DataTextField = "Distribution";
            ddlDistribution.DataValueField = "id";
            ddlDistribution.DataBind();
        }

        protected void btnCancelAdd_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/View.aspx?action=ucProductView");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            int status = ckCongbo.Checked ? 0 : 1;
            var product = new ProductInfo
                              {
                                  Id = txtId.Text,
                                  Name = txtName.Text,
                                  Detail = CKEditor1.Text,
                                  Price = float.Parse(txtPrice.Text.Trim()),
                                  PriceNew = float.Parse(txtPriceNew.Text.Trim()),
                                  Date = DateTime.Parse(txtDate.Text).ToString("yyyy-MM-dd"),
                                  Distribution_Id = Int32.Parse(ddlDistribution.SelectedValue),
                                  GroupProduct_Id = Int32.Parse(ddlGroupProduct.SelectedValue),
                                  Order = Int32.Parse(txtOrder.Text),
                                  Status = status
                              };
            for (int i = 0; i < gvImage.Rows.Count; i++)
            {
                var rdoCheck = (RadioButton) gvImage.Rows[i].FindControl("rdoCheck");
                if (rdoCheck.Checked)
                {
                    var hfImg = (HiddenField) gvImage.Rows[i].FindControl("HfImg");
                    product.Image = hfImg.Value;
                    break;
                }
            }

            //var names = new string[2];
            //names[0] = MapPath(product.Image);
            //names[1] = product.Image.Substring(product.Image.LastIndexOf('/') + 1);
            //_filelist.Add(names);
            //_algorithm.UploadImage(_filelist, product.Id);

            var dtImgs = Session["DataTableImages"] as DataTable;
            var productImgInfo = new ProductImgInfo {Product_Id = txtId.Text.Trim()};

            if (Int32.Parse(Request.QueryString["in"]) == 1)
            {
                _productService.Product_Insert(product);
                if (dtImgs.Rows.Count > 0)
                {
                    for (int i = 0; i < dtImgs.Rows.Count; i++)
                    {
                        productImgInfo.Images = dtImgs.Rows[i]["Image"].ToString();
                        _productImgService.ProductImg_Insert(productImgInfo);
                    }
                }
            }
            else
            {
                _productService.Product_Update(product);
                if (dtImgs.Rows.Count > 0)
                {
                    for (int i = 0; i < dtImgs.Rows.Count; i++)
                    {
                        _productImgService.ProductImg_Delete(txtId.Text.Trim());
                        productImgInfo.Images = dtImgs.Rows[i]["Image"].ToString();
                        _productImgService.ProductImg_Update(productImgInfo);
                    }
                }
            }
            Response.Redirect("~/Admin/View.aspx?action=ucProductView");
        }

        protected void btnSaveAndNew_Click(object sender, EventArgs e)
        {
            int status = ckCongbo.Checked ? 0 : 1;
            var product = new ProductInfo
                              {
                                  Id = txtId.Text,
                                  Name = txtName.Text,
                                  Detail = CKEditor1.Text,
                                  Price = float.Parse(txtPrice.Text.Trim()),
                                  PriceNew = float.Parse(txtPriceNew.Text.Trim()),
                                  Date = DateTime.Parse(txtDate.Text).ToString("yyyy-MM-dd"),
                                  Distribution_Id = Int32.Parse(ddlDistribution.SelectedValue),
                                  GroupProduct_Id = Int32.Parse(ddlGroupProduct.SelectedValue),
                                  Order = Int32.Parse(txtOrder.Text),
                                  Status = status
                              };
            for (int i = 0; i < gvImage.Rows.Count; i++)
            {
                var rdoCheck = (RadioButton) gvImage.Rows[i].FindControl("rdoCheck");
                if (rdoCheck.Checked)
                {
                    var hfImg = (HiddenField) gvImage.Rows[i].FindControl("HfImg");
                    product.Image = hfImg.Value;
                    break;
                }
            }

            //var names = new string[2];
            //names[0] = MapPath(product.Image);
            //names[1] = product.Image.Substring(product.Image.LastIndexOf('/') + 1);
            //_filelist.Add(names);
            //_algorithm.UploadImage(_filelist, product.Id);

            var dtImgs = Session["DataTableImages"] as DataTable;
            var productImgInfo = new ProductImgInfo {Product_Id = txtId.Text.Trim()};

            if (Int32.Parse(Request.QueryString["in"]) == 1)
            {
                _productService.Product_Insert(product);
                if (dtImgs.Rows.Count > 0)
                {
                    for (int i = 0; i < dtImgs.Rows.Count; i++)
                    {
                        productImgInfo.Images = dtImgs.Rows[i]["Image"].ToString();
                        _productImgService.ProductImg_Insert(productImgInfo);
                    }
                }
            }
            else
            {
                _productService.Product_Update(product);
                if (dtImgs.Rows.Count > 0)
                {
                    for (int i = 0; i < dtImgs.Rows.Count; i++)
                    {
                        _productImgService.ProductImg_Delete(txtId.Text.Trim());
                        productImgInfo.Images = dtImgs.Rows[i]["Image"].ToString();
                        _productImgService.ProductImg_Update(productImgInfo);
                    }
                }
            }
            RefreshControl();
        }


        protected void btnUploadImg_Click(object sender, EventArgs e)
        {
            DataTable dtImages;
            if (Session["DataTableImages"] == null)
            {
                dtImages = new DataTable();
                dtImages.Columns.Add("Image", typeof (string));
                DataRow rows = dtImages.NewRow();
                rows["Image"] = txtImage.Text.Trim();
                dtImages.Rows.Add(rows);
                txtImage.Text = string.Empty;
                gvImage.DataSource = dtImages;
                gvImage.DataBind();
                if (gvImage.Rows.Count != 0)
                {
                    var rdoCheck = (RadioButton) gvImage.Rows[0].FindControl("rdoCheck");
                    if (rdoCheck != null) rdoCheck.Checked = true;
                }
            }
            else
            {
                dtImages = (DataTable) Session["DataTableImages"];
                DataRow rows = dtImages.NewRow();
                rows["Image"] = txtImage.Text.Trim();
                dtImages.Rows.Add(rows);
                txtImage.Text = string.Empty;
                gvImage.DataSource = dtImages;
                gvImage.DataBind();
                if (gvImage.Rows.Count != 0)
                {
                    var rdoCheck = (RadioButton) gvImage.Rows[0].FindControl("rdoCheck");
                    if (rdoCheck != null) rdoCheck.Checked = true;
                }
            }
            Session["DataTableImages"] = dtImages;
        }

        protected void gvImage_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvImage.PageIndex = e.NewPageIndex;
            gvImage.DataSource = Session["DataTableImages"];
            gvImage.DataBind();
        }

        protected void gvImage_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //string image = e.CommandArgument.ToString();
            //if(e.CommandName=="Delete")
            //{
            //    DataTable dataTable = Session["DataTableImages"] as DataTable;
            //    DataRow row = dataTable.Rows.Find();
            //    row.Delete();
            //}
        }

        //protected void gvImage_RowDeleting(object sender, GridViewDeleteEventArgs e)
        //{
        //    string image = gvImage.DataKeys[e.RowIndex].Value.ToString();
        //    DataTable dataTable = Session["DataTableImages"] as DataTable;
        //    DataRow row = dataTable.Rows.Find(image);
        //    row.Delete();
         
        //}
    }
}